from fastapi import Request, status
from fastapi.responses import JSONResponse
from fastapi import HTTPException
from fastapi.exceptions import RequestValidationError

from .response_json import error_json
from .basemodel import CustomResponse, CustomMessageType


class BusinessException(HTTPException):
    """
    自定义异常类型，继承HTTPException
    """

    def __init__(self, code: str):
        self.error_code = code
        self.error_message = error_json[code]
        super().__init__(status_code=status.HTTP_400_BAD_REQUEST, detail=self.error_message)


async def global_exception_handler(request: Request, exc: Exception):
    message_type, message_code, message_desc = None, None, None

    if isinstance(exc, RequestValidationError):
        message_type = CustomMessageType.validation
        code = status.HTTP_422_UNPROCESSABLE_ENTITY
        message_code = None
        message_desc = str(exc)
    elif isinstance(exc, BusinessException):
        message_type = CustomMessageType.business
        code = status.HTTP_400_BAD_REQUEST
        message_code = exc.error_code
        message_desc = exc.error_message
    elif isinstance(exc, HTTPException):
        message_type = CustomMessageType.server
        code = str(exc.status_code)
        message_code = exc.detail
        message_desc = error_json[exc.detail]
    else:
        message_type = CustomMessageType.server
        code = status.HTTP_500_INTERNAL_SERVER_ERROR
        message_code = str(exc)
        message_desc = error_json[message_code]

    response_dict = {
        'code': code,
        'message': {
            'type': message_type,
            'code': message_code,
            'desc': message_desc
        },
        'data': {},
    }
    return JSONResponse(
        status_code=int(code),
        content=CustomResponse(**response_dict).dict(exclude_none=True),
    )
